/** niushop 装修的语言包路径 往咱们得系统里兼容了一下 修改了部分配置 */
import { i18n } from '@/plugins/vueI18n'
import useNiushopAppStore from '@/stores/modules/app'

const t = (message: string) => {
  const route = useNiushopAppStore().route
  const path = route.path
  const file =
    path == '/' ? 'index' : path.replace(/^(\/admin\/|\/site\/|\/)/, '').replaceAll('/', '.')
  const key = `${file}.${message}`
  console.log(key)
  // //@ts-ignore
  return i18n.global.t(key) != key ? i18n.global.t(key) : i18n.global.t(message)
}

/**
 *
 * @param locale 设置语言
 */
const setI18nLanguage = (locale: string) => {
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale
  } else {
    i18n.global.locale = locale
  }
  let html = document.querySelector('html')
  html && html.setAttribute('lang', locale)
}
/**
 * 加载语言包
 * 暂时没用到
 * @param path
 * @param locale
 * @returns
 */
const loadLocaleMessages = async (app: string, path: string, locale: string) => {
  try {
    const file =
      path == '/' ? 'index' : path.replace(/^(\/admin\/|\/site\/|\/)/, '').replaceAll('/', '.')
    console.log(app)
    console.log(file)

    // 引入语言包文件
    const messages = await import(
      app
        ? `@/views/addon/${app}/lang/${locale}/${file}.json`
        : `@/views/app/lang/${locale}/${file}.json`
    )
    // const messages = await import('@/views/app/lang/zh-cn/diy.edit.json')

    let data: Record<string, string> = {}
    Object.keys(messages.default).forEach((key) => {
      data[`${file}.${key}`] = messages.default[key]
    })
    // 查询插件的公共语言包
    if (app) {
      try {
        const messagesCommon = await import(`@/${app}/lang/${locale}/common.json`)
        Object.keys(messagesCommon.default).forEach((key) => {
          data[`${file}.${key}`] = messagesCommon.default[key]
        })
      } catch (e) {
        // console.log('未找到插件公共语言包')
      }
    }

    i18n.global.mergeLocaleMessage(locale, data)
    setI18nLanguage(locale)
    return nextTick()
  } catch (e) {
    setI18nLanguage(locale)
    return nextTick()
  }
}
export { t, loadLocaleMessages }

export default {
  install(app: any) {
    //注册i18n
    app.use(i18n)
  }
}
